package com.hs.pre.page;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.hs.HsBase;
import com.hs.core.db.DBOperator;
import com.hs.core.db.DatabaseConnection;
import com.hs.pre.model.PreEntry;



/***
 * 分页查询类
 * @author Administrator
 *
 */
public class PageQuery {
	/**
	 * 反向加载数据
	 */
	private ReverseLoadData reverseLoadData;
	private PageUtil pageUtil ;
	public PageQuery(String sql,Object [] sqlParam,PageParam pageParam,ReverseLoadData reverseLoadData) throws Exception
	{
		this.reverseLoadData = reverseLoadData;
		this.init(sql, sqlParam, pageParam);
	}
	public PageQuery(String sql,Object [] sqlParam,PageParam pageParam) throws Exception
	{
		this.init(sql, sqlParam, pageParam);		
 	}
	
	public void init(String sql,Object [] sqlParam,PageParam pageParam)throws Exception
	{

		if(pageParam.isIdentifier())
		{
			sql = pageParam.getBaseSql();
			sqlParam = pageParam.getBaseParam();
			
		}else
		{
			pageParam.setBaseParam(sqlParam);
			pageParam.setBaseSql(sql);
		}
		
		PageImpl pageImpl = new PageImpl();
		pageImpl.setPageSize(pageParam.getPageSize());
		pageImpl.setThisPageNumber(pageParam.getThisPageNumber());
		/**
		 * 当前页末位置行数
		 */
		int eNum = pageImpl.getPageSize()*pageImpl.getThisPageNumber();
		/**
		 * 当前页首位置行数
		 */
		int sNum = eNum-pageImpl.getPageSize();
        
		String sqlExe = "SELECT * FROM (select ROW_NUMBER() OVER () AS R,tt.* " +
				" from ("+sql+") tt )" +
				" AS A  where A.R >"+sNum+
				" and A.R<="+eNum;
		
		DBOperator dbo = null;
			dbo = DatabaseConnection.getDBOperator();
		List listResult = new ArrayList();
		List list = dbo.select(sqlExe,sqlParam);
		Iterator iterator = list.iterator();
		
		while(iterator.hasNext())
		{
			Map row = (Map)iterator.next();
			if(reverseLoadData != null)
			{
				listResult.add(this.reverseLoadData.load(row));
			}else
			{
				listResult.add(row);
			}
		}
		
		/**********设置总页数**********************/
		String  maxSql = "select count(*) mNum from ("+sql+") as a";
		list = dbo.select(maxSql,sqlParam);
		iterator = list.iterator();
		if(iterator.hasNext())
		{
			Map map = (Map)iterator.next();
			pageImpl.setTotalNumber(((Integer)map.get("mNum")).intValue());
		}
		/******************/
		this.pageUtil = new PageUtil(pageImpl,pageParam);
		/***
		 * 设置查询数据
		 */
		pageUtil.setResultList(listResult);
		
	}
	
	public PageUtil getPageUtil()
	{
		
		return pageUtil;
	}

	public ReverseLoadData getReverseLoadData() {
		return reverseLoadData;
	}

	public void setReverseLoadData(ReverseLoadData reverseLoadData) {
		this.reverseLoadData = reverseLoadData;
	}
	

}
